package com.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(urlPatterns = {"/student/*", "/teacher/*", "/admin/*"})
public class LoginFilter implements Filter {
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession();
        
        // 检查用户是否已登录
        Object user = session.getAttribute("user");
        String userType = (String) session.getAttribute("userType");
        
        if (user == null) {
            // 未登录，重定向到登录页面
            resp.sendRedirect(req.getContextPath() + "/login");
            return;
        }
        
        // 检查用户访问权限
        String requestURI = req.getRequestURI();
        if (!hasPermission(requestURI, userType)) {
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "没有访问权限");
            return;
        }
        
        chain.doFilter(request, response);
    }
    
    private boolean hasPermission(String uri, String userType) {
        if (userType == null) return false;
        
        System.out.println("=== 权限检查 ===");
        System.out.println("检查URI: " + uri);
        System.out.println("用户类型: " + userType);
        
        // 获取项目上下文路径后的部分
        String contextPath = uri.substring(uri.indexOf("/", 1));
        System.out.println("处理后的路径: " + contextPath);
        
        // 修改路径匹配逻辑
        if (contextPath.startsWith("/student/") && "student".equals(userType)) return true;
        if (contextPath.startsWith("/teacher/") && "teacher".equals(userType)) return true;
        if (contextPath.startsWith("/admin/") && "admin".equals(userType)) return true;
        
        System.out.println("权限检查失败");
        return false;
    }
    
    @Override
    public void destroy() {
    }
}
